//
//  CQTool.m
//  coninbase_data
//
//  Created by 2.5 on 2021/3/18.
//  Copyright © 2021 ChinaRainbow-iOS. All rights reserved.
//

#import "CQTool.h"
#import "UIView+main.h"

//#import "YFUserModel.h"
@implementation CQTool
{
    NSDictionary *_jyDic;
}
+(CQTool*)shareSelf
{
    static CQTool *tool = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tool = [[CQTool alloc] init];
    });
    [[NSNotificationCenter defaultCenter] addObserver:tool selector:@selector(requestAllJinYan:) name:@"ccJYGroup" object:nil];
    return tool;
}
-(void)requestAllJinYan:(NSNotification*)nf
{
    NSDictionary *infoDic = nf.object;
    if([infoDic isKindOfClass:[NSDictionary class]]){
        if(infoDic == _jyDic){
            return;
        }
        _jyDic = infoDic;
    }
}
+(NSString *)notNilCheck:(NSString *)str
{
    NSString *resultStr = [NSString stringWithFormat:@"%@",str];
    if([[resultStr uppercaseString] isEqualToString:@"NULL"]||[[resultStr uppercaseString] isEqualToString:@"NIL"]){
        return @"--";
    }
    return resultStr;
}
+(void)upLoadActionWIth:(NSString *)bizType andEventId:(NSString *)eventId andExtParam:(NSDictionary *)extParam
{
    if([extParam isKindOfClass:[NSDictionary class]]){
        NSMutableDictionary *infoDic = [[NSMutableDictionary alloc] initWithDictionary:extParam];
        [infoDic setObject:NotNilStr([self getUUID]) forKey:@"uuid"];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [MPRemoteLoggingInterface writeLogWithBizType:bizType eventId:eventId extParam:infoDic];
//            [MPRemoteLoggingInterface upload];
//        });
    }
}
+(NSString*)getUUID
{
    NSString *UDID = [[NSUserDefaults standardUserDefaults] objectForKey:@"CCCUDID"];
    if(UDID&&UDID.length){
        return UDID;
    }
    UDID = [self load:@"CCCUDID"];
    if(!UDID||!UDID.length){
        CFUUIDRef puuid = CFUUIDCreate(nil);
        CFStringRef uuidString = CFUUIDCreateString(nil, puuid);
        NSString *result = (NSString *)CFBridgingRelease(CFStringCreateCopy(NULL, uuidString));
        NSMutableString *tmpResult = result.mutableCopy;
        // 去除“-”
        NSRange range = [tmpResult rangeOfString:@"-"];
        while (range.location != NSNotFound) {
            [tmpResult deleteCharactersInRange:range];
            range = [tmpResult rangeOfString:@"-"];
        }
        [[NSUserDefaults standardUserDefaults] setObject:tmpResult forKey:@"CCCUDID"];
        [self save:@"CCCUDID" data:[tmpResult dataUsingEncoding:NSUTF8StringEncoding]];
        NSLog(@"%@",[self load:@"CCCUDID"]);
        return tmpResult;
    }else{
        return UDID;
    }
}
+ (void)save:(NSString *)service data:(id)data {

    //Get search dictionary

    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];

    //Delete old item before add new item

    SecItemDelete((CFDictionaryRef)keychainQuery);

    //Add new object to search dictionary(Attention:the data format)

    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(id)kSecValueData];

    //Add item to keychain with the search dictionary

    SecItemAdd((CFDictionaryRef)keychainQuery, NULL);

}

 

+ (NSString *)load:(NSString *)service {

    id ret = nil;

    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];

    //Configure the search setting

    //Since in our simple case we are expecting only a single attribute to be returned (the password) we can set the attribute kSecReturnData to kCFBooleanTrue

    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];

    [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];

    CFDataRef keyData = NULL;

    if (SecItemCopyMatching((CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {

        @try {

            ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];

        } @catch (NSException *e) {

            NSLog(@"Unarchive of %@ failed: %@", service, e);

        } @finally {

        }

    }

    if (keyData)

        CFRelease(keyData);
    if(ret){
        return  [[NSString alloc] initWithData:ret encoding:NSUTF8StringEncoding];
    }else{
        return @"";
    }

}
+ (NSMutableDictionary *)getKeychainQuery:(NSString *)service {

    return [NSMutableDictionary dictionaryWithObjectsAndKeys:

            (id)kSecClassGenericPassword,(id)kSecClass,

            service, (id)kSecAttrService,

            service, (id)kSecAttrAccount,

            (id)kSecAttrAccessibleAfterFirstUnlock,(id)kSecAttrAccessible,

            nil];

}
+(void)changeButtonIndex:(UIButton *)sender
{
    CGFloat btnImageWidth = sender.imageView.bounds.size.width;
    CGFloat btnLabelWidth = sender.titleLabel.bounds.size.width;
    CGFloat margin = 3;
    
    btnImageWidth += margin;
    btnLabelWidth += margin;
    [sender setTitleEdgeInsets:UIEdgeInsetsMake(0, -btnImageWidth, 0, btnImageWidth)];
    [sender setImageEdgeInsets:UIEdgeInsetsMake(0, btnLabelWidth, 0, -btnLabelWidth)];
}
//图片在上，文字在xia
+(void)changeButtonTopIndex:(UIButton *)sender
{
    //设置文字偏移：向下偏移图片高度＋向左偏移图片宽度 （偏移量是根据［图片］大小来的，这点是关键）
    sender.titleEdgeInsets = UIEdgeInsetsMake(sender.imageView.frame.size.height+3, -sender.imageView.frame.size.width, 0, 0);

    //设置图片偏移：向上偏移文字高度＋向右偏移文字宽度 （偏移量是根据［文字］大小来的，这点是关键）
    NSLog(@"%@",NSStringFromCGSize(sender.titleLabel.bounds.size));
    sender.imageEdgeInsets = UIEdgeInsetsMake(-sender.titleLabel.frame.size.height-3,sender.titleLabel.bounds.size.width/2.0,0,-sender.titleLabel.bounds.size.width/2.0);
}
+(CAGradientLayer*)addBottomLayerWith:(UIView *)vv andArray:(NSArray *)array andCorner:(CGFloat)radio
{
    CAGradientLayer *gl = [CAGradientLayer layer];
    gl.frame = CGRectMake(vv.ccx,vv.ccy,vv.ccwidth,vv.ccheight);
    gl.startPoint = CGPointMake(0, 0);
    gl.endPoint = CGPointMake(1, 1);
    gl.colors = array;
    gl.locations = @[@(1.0),@(0.0f)];
    gl.cornerRadius = radio;
    [vv.superview.layer addSublayer:gl];
//    [vv.superview.layer insertSublayer:gl atIndex:0];
    return gl;
}
+(CAGradientLayer*)addBottomLayer2With:(UIView *)vv andArray:(NSArray *)array andCorner:(CGFloat)radio
{
    CAGradientLayer *gl = [CAGradientLayer layer];
    gl.frame = CGRectMake(0,0,vv.ccwidth,vv.ccheight);
    gl.startPoint = CGPointMake(0, 0);
    gl.endPoint = CGPointMake(0, 1);
    gl.colors = array;
    gl.cornerRadius = radio;
    [vv.layer addSublayer:gl];
    return gl;
}
+(NSString *)autoCellChange:(NSString *)allStr
{
    NSString *resultStr = NotNilStr(allStr);
    long long longValue = [NotNilStr(allStr) longLongValue];
    if(longValue>10000){
        resultStr = [NSString stringWithFormat:@"%.1f万",longValue/10000.0];
    }else if(longValue>1000000){
        resultStr = [NSString stringWithFormat:@"%.1f百万",longValue/1000000.0];
    }else if(longValue>10000000){
        resultStr = [NSString stringWithFormat:@"%.1f千万",longValue/10000000.0];
    }else if(longValue>100000000){
        resultStr = [NSString stringWithFormat:@"%.1f亿",longValue/100000000.0];
    }
    if([resultStr containsString:@".0"]){
        NSMutableString *ss = [[NSMutableString alloc] initWithString:resultStr];
        [ss deleteCharactersInRange:[resultStr rangeOfString:@".0"]];
        return  ss;
    }
    return  resultStr;
}
+ (NSString *)createUUID

{

    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);

    CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);

    NSString *uuid = [NSString stringWithString:(__bridge NSString *)uuid_string_ref];

    CFRelease(uuid_ref);

    CFRelease(uuid_string_ref);

    return [uuid lowercaseString];

}
+(NSString *)delegteSpace:(NSString *)baseStr
{
    NSMutableString *ss = [[NSMutableString alloc] initWithString:NotNilStr(baseStr)];
        NSRange range = NSMakeRange(0, baseStr.length);
        [ss replaceOccurrencesOfString:@" "withString:@""options:NSLiteralSearch range:range];
        range = NSMakeRange(0, ss.length);
        [ss replaceOccurrencesOfString:@"\n"withString:@""options:NSLiteralSearch range:range];
        return  ss;
}
+(NSArray *)returnUserInfos
{
    NSMutableArray *resultArray = [[NSMutableArray alloc] init];
//    NSArray *auths = [YFUserModel.shareModel.auths copy];
//    if ([YFUserModel.shareModel.auths isKindOfClass:[NSString class]]) {
//        NSString *authsString = (NSString *)YFUserModel.shareModel.auths;
//        authsString =  [self delegteSpace:authsString];
//        NSData *jsonData = [authsString dataUsingEncoding:NSUTF8StringEncoding];
//        NSError *err;
//        auths = [NSJSONSerialization JSONObjectWithData:jsonData
//                                                options:NSJSONReadingMutableContainers
//                                                  error:&err];
//        if (err || [auths isKindOfClass:[NSArray class]] == NO) {
//            return resultArray;
//        }
//    }
//    for (NSDictionary *dict in auths) {
//        NSString *key = dict[@"key"];
//        if(![key isEqualToString:@"weibo"]){
//            [resultArray addObject:dict];
//        }
//    }
    return resultArray;
}
+(CGFloat)statusBarHeight
{
    return [UIApplication sharedApplication].statusBarFrame.size.height;
}
@end
